﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;
using System.Windows.Forms;

namespace meituan
{
    public partial class FormMain : Form
    {
        Thread thread;
        /*public void test()
        {
            string html = File.ReadAllText("diqu.txt");
            var doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(html);
            HtmlAgilityPack.HtmlNode hd = doc.DocumentNode;
            HtmlAgilityPack.HtmlNodeCollection nodes = hd.SelectNodes(".//a");
            Dictionary<string, string> dic = new Dictionary<string, string>();
            foreach (HtmlAgilityPack.HtmlNode node in nodes)
            {
                dic.Add(node.InnerText, node.Attributes["href"].Value);

            }
            string json = JsonConvert.SerializeObject(dic);
            Console.WriteLine(json);
            File.WriteAllText("cityLink.json", json);
            //Dictionary<string, string> DicContent = (Dictionary<string, string>)JsonConvert.DeserializeObject(Contentjson.ToString());
        }*/
        /*public void test()
        {
            string url = @"https://bj.meituan.com/";
            System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
            httpWebRequest.Method = "GET";
            httpWebRequest.Timeout = 20000;
            httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36";
            System.Net.HttpWebResponse httpWebResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse();
            string[] cookies = httpWebResponse.Headers.GetValues("Set-Cookie");
            Console.WriteLine(cookies[0]);
            Console.WriteLine(cookies[1]);
            Console.WriteLine(cookies[2]);
            Console.WriteLine(cookies[3]);
            httpWebResponse.Close();

            *//*string url = @"https://www.meituan.com/meishi/187778231/";
            string html = Utils.HttpGet(url);
            if (html != null)
            {
                Regex regex = new Regex(@"<title>.*?<title>");
                Match match = regex.Match(html);
                if (match.Success)
                {
                    Console.WriteLine(match.ToString());
                }
                else
                {
                    Console.WriteLine("没有匹配到内容!");
                }
            }
            else
            {
                Console.WriteLine("请求失败");
            }*//*

        }*/

        public FormMain()
        {
            InitializeComponent();
        }

        private void buttonSelect_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = false;//该值确定是否可以选择多个文件
            dialog.Title = "请选择文件夹";
            dialog.Filter = "所有文件(*.*)|*.*";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string file = dialog.FileName;
                textBoxFile.Text = file;
            }
        }

        private void buttonImport_Click(object sender, EventArgs e)
        {
            string file = textBoxFile.Text;
            if (file == String.Empty)
            {
                MessageBox.Show("请选择文件！");
                return;
            }
            DataTable dt = Excel.ExcelToTable(file);
            listViewDianpu.Columns.Add("");
            listViewDianpu.Columns[0].Width = 40;

            listViewDianpu2.Columns.Add("");
            listViewDianpu2.Columns[0].Width = 40;
            try
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    listViewDianpu.Columns.Add(dt.Columns[i].ColumnName);
                    listViewDianpu.Columns[i + 1].Width = 90;

                    listViewDianpu2.Columns.Add(dt.Columns[i].ColumnName);
                    listViewDianpu2.Columns[i + 1].Width = 90;
                }
            }
            catch (System.NullReferenceException)
            {
                MessageBox.Show("NullReferenceException");
                return;
            }
            
            
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                ListViewItem item = new ListViewItem();
                item.SubItems[0].Text = i.ToString();
                for (int j = 1; j < listViewDianpu.Columns.Count; j++)
                {
                    try
                    {
                        item.SubItems.Add(dt.Rows[i][listViewDianpu.Columns[j].Text].ToString());
                    }
                    catch
                    {
                        MessageBox.Show("数据异常");
                        return;
                    }
                    
                }
                listViewDianpu.Items.Add(item);
            }

            dt.Clear();
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            int selectCount = listViewDianpu.SelectedItems.Count;
            if (selectCount > 0)
            {
                for (int i = 0; i < selectCount; i++)
                {
                    int index = Convert.ToInt32(listViewDianpu.SelectedItems[i].Text);
                    listViewDianpu2.Items.Add((ListViewItem)listViewDianpu.Items[index].Clone());
                }
            }
        }

        private void buttonRemove_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in listViewDianpu2.SelectedItems)
            {
                if (item.Selected)
                {
                    item.Remove();
                }
            }
        }

        private void buttonSelectAll_Click(object sender, EventArgs e)
        {
            listViewDianpu2.Items.Clear();
            for (int i = 0; i < listViewDianpu.Items.Count; i++)
            {
                int index = Convert.ToInt32(listViewDianpu.Items[i].Text);
                listViewDianpu2.Items.Add((ListViewItem)listViewDianpu.Items[index].Clone());
            }
        }

        private void buttonClear_Click(object sender, EventArgs e)
        {
            listViewDianpu2.Items.Clear();
        }

        private void buttonSart_Click(object sender, EventArgs e)
        {
            if (buttonStart.Text == "开始")
            {
                Dictionary<string, string> config = Utils.getConfig();
                if (config == null)
                {
                    MessageBox.Show("请设置配置");
                    return;
                }

                if (listViewDianpu2.Items.Count == 0)
                {
                    MessageBox.Show("请先添加");
                    return;
                }

                foreach (Control ctl in this.Controls)
                {
                    if (ctl is Button)
                    {
                        Button btn = ctl as Button;
                        btn.Enabled = false;
                    }
                }
                buttonStart.Text = "停止";
                buttonStart.Enabled = true;

                if (thread == null)
                {
                    run(config);
                }
                else
                {
                    MessageBox.Show("线程正在执行");
                }
                
            }
            else
            {
                thread.Abort();
                while (true)
                {
                    Thread.Sleep(1000);
                    Console.WriteLine(thread.IsAlive);
                    if (!thread.IsAlive)
                    {
                        thread = null;
                        foreach (Control ctl in this.Controls)
                        {
                            if (ctl is Button)
                            {
                                Button btn = ctl as Button;
                                btn.Enabled = true;
                            }
                        }
                        buttonStart.Text = "开始";
                        break;
                    }
                }
            }
        }

        private void SettingToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormSetting form = new FormSetting();
            form.ShowDialog();
        }

        private void HelpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormHelp form = new FormHelp();
            form.ShowDialog();
        }

        private void buttonPinglun_Click(object sender, EventArgs e)
        {
            FormPinglun form = new FormPinglun();
            form.ShowDialog();
        }

        private void run(Dictionary<string, string> config)
        {
            Dictionary<string, string> city = Utils.getCityList();
            Dictionary<string, string> cityLink = Utils.getCityLinkList();
            ArrayList arr = new ArrayList();
            foreach (ListViewItem item in listViewDianpu2.Items)
            {
                string diqu = item.SubItems[1].Text;
                string dianpu = item.SubItems[2].Text;
                if (!city.Keys.Contains(diqu))
                {
                    Invoke(new Action<string>((x) => {
                        textBoxInfo.Text += x.ToString();
                        textBoxInfo.SelectionStart = textBoxInfo.Text.Length;
                        textBoxInfo.ScrollToCaret();
                    }), diqu + "不存在\n");
                    continue;
                }
                string cityid = city[diqu];
                string referer = $"https:{cityLink[diqu]}/s/{dianpu}/";

                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic.Add("diqu", diqu);
                dic.Add("dianpu", dianpu);
                dic.Add("cityid", cityid);
                dic.Add("referer", referer);

                arr.Add(dic);
            }

            thread = new Thread(new ThreadStart(() => {
                Random rd = new Random();
                int num = 0;
                foreach (Dictionary<string, string> i in arr)
                {
                    string diqu = i["diqu"];
                    string dianpu = i["dianpu"];
                    string cityid = i["cityid"];
                    string referer = i["referer"];
                    Invoke(new Action<string>((x) => {
                        textBoxInfo.Text += x.ToString();
                        textBoxInfo.SelectionStart = textBoxInfo.Text.Length;
                        textBoxInfo.ScrollToCaret();
                    }), String.Format("开始执行：{0}_{1}\n", diqu, dianpu));

                    int limit = 32;
                    int offset = 0;
                    string fileName = diqu + "_" + dianpu;
                    while (true)
                    {
                        string uuid = Utils.GetUuid();
                        string url = $"https://apimobile.meituan.com/group/v4/poi/pcsearch/{cityid}?uuid={uuid}&limit={limit}&offset={offset}&cateId=-1&q={dianpu}";
                        Invoke(new Action<string>((x) => {
                            textBoxInfo.Text += x.ToString();
                            textBoxInfo.SelectionStart = textBoxInfo.Text.Length;
                            textBoxInfo.ScrollToCaret();
                        }), url + "\n");
                        Console.WriteLine(url);

                        bool flag = false;
                        if (config["isProxy"] == "1")
                        {
                            flag = true;
                        }
                        string res = Utils.HttpGet(url, referer, flag);
                        Console.WriteLine(res);
                        if (res == null)
                        {
                            Invoke(new Action<string>((x) => {
                                textBoxInfo.Text += x.ToString();
                                textBoxInfo.SelectionStart = textBoxInfo.Text.Length;
                                textBoxInfo.ScrollToCaret();
                            }), "请求失败！\n");
                            break;
                        }
                        JObject jo = (JObject)JsonConvert.DeserializeObject(res);
                        //var total = jo["data"]["totalCount"];

                        string strData = "";
                        int counter = 0;
                        foreach (JObject data in jo["data"]["searchResult"])
                        {
                            counter++;
                            strData += data["id"] + "," +
                            Convert.ToString(data["title"]).Replace(',', '，') + "," +
                            Convert.ToString(data["backCateName"]).Replace(',', '，') + "," +
                            Convert.ToString(data["address"]).Replace(',', '，') + "," +
                            Convert.ToString(data["areaname"]).Replace(',', '，') + "," +
                            data["avgprice"] + "," +
                            data["avgscore"] + "," +
                            Convert.ToString(data["imageUrl"]).Replace("w.h/", "") + "\n";
                        }

                        if (counter == 0)
                        {
                            Invoke(new Action<string>((x) => {
                                textBoxInfo.Text += x.ToString();
                                textBoxInfo.SelectionStart = textBoxInfo.Text.Length;
                                textBoxInfo.ScrollToCaret();
                            }), String.Format("{0}_{1} 完毕\n", diqu, dianpu));
                            break;
                        }
                        Excel.WriteToCSV(config["dataPath"] + "\\店铺", fileName, strData);
                        num = rd.Next(int.Parse(config["timeMin"]), int.Parse(config["timeMax"]));
                        Invoke(new Action<string>((x) => {
                            textBoxInfo.Text += x.ToString();
                            textBoxInfo.SelectionStart = textBoxInfo.Text.Length;
                            textBoxInfo.ScrollToCaret();
                        }), strData + "\n等待" + num + "后执行下一次请求\n");
                        Thread.Sleep(num * 1000);
                        offset += limit;
                    }
                    
                    num = rd.Next(int.Parse(config["timeMin"]), int.Parse(config["timeMax"]));
                    Invoke(new Action<string>((x) => {
                        textBoxInfo.Text += x.ToString();
                        textBoxInfo.SelectionStart = textBoxInfo.Text.Length;
                        textBoxInfo.ScrollToCaret();
                    }), "等待" + num + "后执行下一次请求\n");
                    Thread.Sleep(num * 1000);

                }
                Invoke(new Action<string>((x) => {
                    textBoxInfo.Text += x.ToString();
                    textBoxInfo.SelectionStart = textBoxInfo.Text.Length;
                    textBoxInfo.ScrollToCaret();
                    foreach (Control ctl in this.Controls)
                    {
                        if (ctl is Button)
                        {
                            Button btn = ctl as Button;
                            btn.Enabled = true;
                        }
                    }
                    buttonStart.Text = "开始";
                }), "全部完毕");
                MessageBox.Show("全部完毕");
            }));
            thread.IsBackground = true;
            thread.Start();
        }
    }
}
